<template>
  <el-popover
    v-model:visible="data.isPopoverOpen"
    placement="right-start"
    trigger="contextmenu"
    :width="200"
    teleported
    @before-enter="() => {
      emit('resetAllGroupItem', getId())
    }"
  >
    <template #reference>
      <div class="popover-reference-wrapper" style="width: 100%;">
        <el-tooltip :content="group.descr" :disabled="!group.descr" placement="top" :show-after="300" :hide-after="0">
          <el-row
            v-show="!data.isEditMode"
            @click.left="() => {
              emit('changeCurGroup', getId(), group.gname, group.icon)
            }"
            @dblclick="dbClick"
            title="双击编辑，右键查看更多选项"
            :class="{
              'groups-item': true,
              'active': isSelected
            }"
          >
            <el-icon class="icon"><component v-if="!!group.icon" :is="group.icon" /></el-icon>
            <span class="name">{{ group.gname }}</span>
            <span class="badge" v-if="!!group.count">{{ group.count }}</span>
          </el-row>
        </el-tooltip>

        <el-input
          class="group-input"
          v-show="data.isEditMode"
          v-model="data.editGroupName"
        >
          <template #prepend>
            <el-dropdown
              class="icon-dropdown"
              placement="bottom-start"
              trigger="click"
              title="点击更换分组图标"
              max-height="300px"
            >
              <el-button type="primary" :icon="data.selectedIcon"></el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                    style="padding-top: 6px; padding-bottom: 6px;"
                    class="icon-dropdown-item"
                    v-for="icon in data.icons"
                    :key="icon"
                    @click="data.selectedIcon = icon"
                  >
                    <el-icon style="margin-right: 0; font-size: 14px;">
                      <component :is="icon" />
                    </el-icon>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </template>
          <template #append>
            <div style="width: 100%; height: 100%; display: flex; position: relative;">
              <el-button
                type="primary"
                icon="Switch"
                title="切换"
                @click="() => {
                  data.isEditMode = false
                  data.selectedIcon = group.icon
                  data.editGroupName = group.gname
                  data.editGroupDescr = group.descr
                }">
              </el-button>

              <el-popover
                placement="bottom-start"
                title="分组描述"
                :width="200"
                trigger="click"
              >
                <template #reference>
                  <el-button
                    type="primary"
                    icon="Document"
                    title="修改分组描述">
                  </el-button>
                </template>
                <el-input type="textarea" v-model="data.editGroupDescr"></el-input>
              </el-popover>

              <el-button
                type="primary"
                icon="Select"
                title="确定"
                @click="toConfirm">
              </el-button>
            </div>
          </template>
        </el-input>
      </div>
    </template>

    <ul class="more-operation">
      <li @click="toEdit">编辑</li>
      <li @click="openFolderDialog">移入{{ group.folderId ? ' / 移出' : '' }}文件夹</li>
      <li @click="toDelete">删除</li>
    </ul>
  </el-popover>
</template>

<script lang="ts" setup>
import { reactive } from 'vue'
import type { Group } from '@/types/types'
import { updateGroupApi, deleteGroupApi } from '&/group'
import { SUCCESS_CODE } from '@/config/requestCode'
import { openMessage, openConfirmMessageBox } from '@/utils/elComponents'
import { supportIcons } from '@/utils/elementPlusIcon'

const {
  group,
  isSelected
} = defineProps<{
  group: Group,
  isSelected: boolean
}>()
const emit = defineEmits([
  'changeCurGroup',
  'updateGroup',
  'openFolderDialog',
  'resetAllGroupItem',
  'reReq'
])
const data = reactive({
  isEditMode: false,
  iconsSelected: '',
  isPopoverOpen: false,
  editGroupName: group.gname || '',
  editGroupDescr: group.descr || '',
  selectedIcon: group.icon || '',
  icons: supportIcons
})

const getId = () => group.id
const reset = () => {
  data.isEditMode = false
  data.iconsSelected = ''
  data.isPopoverOpen = false
  data.editGroupName = group.gname || ''
  data.editGroupDescr = group.descr || ''
  data.selectedIcon = group.icon || ''
}
defineExpose({ reset, getId })

const toEdit = () => {
  data.isPopoverOpen = false
  data.isEditMode = true
}

const dbClick = () => {
  emit('resetAllGroupItem', getId())
  data.isEditMode = true
}

async function toDelete() {
  data.isPopoverOpen = false

  try {
    await openConfirmMessageBox(`"${group.gname}"分组下的所有待办也将删除! 确定要删除该分组?`, '')
  } catch (err) {
    return
  }

  const resp = await deleteGroupApi(getId())
  if (resp && resp.code == SUCCESS_CODE) {
    openMessage('success', '删除成功')
    setTimeout(emit, 100, 'reReq')
  } else {
    openMessage('error', '删除失败')
  }
}

const toConfirm = () => {
  updateGroupApi({
    id: getId(),
    icon: data.selectedIcon,
    gname: data.editGroupName,
    descr: data.editGroupDescr
  }).then(resp => {
    if (resp && resp.code == SUCCESS_CODE) {
      openMessage('success', '修改成功!')
      emit('updateGroup', getId(), data.editGroupName, data.selectedIcon, data.editGroupDescr)
      data.isEditMode = false
    }
  }, err => {
    openMessage('error', err.Message)
  })
}

const openFolderDialog = () => {
  data.isPopoverOpen =false
  emit('openFolderDialog', getId())
}
</script>

<style lang="scss" scoped>
$itemH: 41px;
@mixin basic-group-item {
  display: flex;
  justify-content: flex-start;
  align-items: center;
  height: $itemH;
  position: relative;
  padding: 10px 5px 10px 10px;
  cursor: pointer;
  border-radius: $border-radius;
  margin-bottom: 5px;
  line-height: 21px;
  &:hover {
    background-color: $hover-color;
  }
  &:after {
    content: '';
    display: block;
    position: absolute;
    left: 0px;
    top: 50%;
    transform: translateY(-50%);
    width: 3px;
    height: 40%;
    border-radius: $border-radius;
    background-color: #5D71BF;
    opacity: 0;
    @include transition('opacity', $default-transition-duration);
  }
  &.active {
    color: $text-color;
    background-color: $hover-color;
    &:after { opacity: 1; }
  }

  .icon {
    position: relative;
    top: 1px;
    margin-right: 15px;
  }

  .badge {
    position: absolute;
    text-align: right;
    width: 20px;
    height: 20px;
    padding: 0;
    text-align: center;
    line-height: 20px;
    border-radius: 50%;
    background-color: #DEDEDE;
    font-size: 12px;
    right: 15px;
    top: 50%;
    margin-top: -10px;
  }
}

.groups-item {
  @include basic-group-item();
}

.more-operation {
  list-style: none;
  font-size: 14px;
  padding: 0;
  li {
    padding: 0 10px;
    background-color: #fff;
    line-height: 2;
    border-radius: $border-radius;
    cursor: pointer;
    @include transition('background-color', $default-transition-duration);
    &:hover {
      background-color: $hover-color;
    }
  }
}

.group-input {
  margin-bottom: 5px;
  height: $itemH;
  ::v-deep(.el-input-group__prepend) {
    padding: 0;
    width: $itemH;
  }
  ::v-deep(.el-input-group__append) {
    padding: 0;
    width: 82px;

    .el-button {
      padding: 0;
      flex-grow: 1;
      flex-shrink: 1;
      width: 33.3333%;
      height: 100%;
      margin: 0;
      font-size: 14px;
      &:hover {
        background-color: $hover-color;
      }
    }
  }
  .icon-dropdown {
    width: 100%;
    height: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    ::v-deep(.el-button) {
      width: 100%;
      height: 100%;
      padding: 0;
      &:hover {
        background-color: $hover-color;
      }
      .el-icon {
        margin: 0;
      }
    }
  }
}

</style>
